using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Collections;

namespace ServerManager.Network
{
    public delegate void HandlerMethod();

    public class NetworkHandler
    {
        private TcpClient client;
        private Byte[] receiveBytes = new Byte[2];
        private List<HandlerInvoker> handlers;

        internal NetworkHandler(TcpClient client)
        {
            this.client = client;
            this.handlers = new List<HandlerInvoker>();

            this.BeginReceive();
        }

        public void AddHandler(MessageType mt, HandlerMethod method)
        {
            this.handlers.Add(new HandlerInvoker(mt, method));
        }

        private void BeginReceive()
        {
            try
            {
                this.client.Client.BeginReceive(receiveBytes, 0, receiveBytes.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
            }
            catch { }
        }

        internal void ReceiveData(IAsyncResult result)
        {
            try
            {
                Int32 bytesRecv = this.client.Client.EndReceive(result);
                if (bytesRecv > 0)
                {
                    try
                    {
                        MessageType mt = (MessageType)Enum.Parse(typeof(MessageType), Encoding.UTF8.GetString(receiveBytes));
                        Console.WriteLine("received {0}", mt.ToString());
                        this.HandleRequestType(mt);
                    }
                    catch { }
                }
            }
            catch { }
            finally
            {

                this.BeginReceive();
            }
        }

        private void HandleRequestType(MessageType mt)
        {
            this.handlers.ForEach(delegate(HandlerInvoker hi)
            {
                if (hi.MessageType == mt)
                    hi.Method();
            });
        }
    }
}
